<template>
    <div>
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="课程码" label-width="70px" prop="courseId">
                <el-input clearable v-model="formInline.courseId" placeholder="请输入课程码"></el-input>
            </el-form-item>
            <el-form-item label="课程名" label-width="70px" prop="courseName">
                <el-input clearable v-model="formInline.courseName" placeholder="请输入课程名"></el-input>
            </el-form-item>
            <el-form-item label="教师" label-width="70px" prop="name">
                <el-input clearable v-model="formInline.name" placeholder="请输入教师名"></el-input>
            </el-form-item>
            <el-form-item label="教室" label-width="70px" prop="className">
                <el-input clearable v-model="formInline.className" placeholder="请输入教室名"></el-input>
            </el-form-item>
            <el-form-item label-width="70px" prop="enable">
                <el-radio v-model="formInline.enable" label="1">已分配</el-radio>
                <el-radio v-model="formInline.enable" label="0">未分配</el-radio>
                <el-radio v-model="formInline.enable" label="">全部</el-radio>
            </el-form-item>
            <el-form-item style="margin-left: 10px">
                <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
                <el-button @click="select" type="primary" icon="el-icon-search">查询</el-button>
                <el-button :disabled="this.batchIds.length===0" type="warning" icon="el-icon-upload2">导出</el-button>
                <el-button :disabled="this.batchIds.length===0" type="warning" icon="el-icon-document-checked"
                           @click="batch('merge')">合并
                </el-button>
                <el-button :disabled="this.batchIds.length===0" type="warning" icon="el-icon-upload2"
                           @click="batch('split')">拆分
                </el-button>
            </el-form-item>
        </el-form>
        <el-checkbox-group v-model="checkArr" size="medium">
            <el-col :span=4 v-for="item in optionalColumnList" :key="item.prop">
                <el-checkbox :label="item.propName" @change="menuChange(item)"></el-checkbox>
            </el-col>
        </el-checkbox-group>
        <el-table @selection-change="handleSelectionChange" border
                  style="width: 100%"
                  ref="multipleTable"
                  :data="tableData">
            <span><el-table-column type="selection" width="55" @click="batch()"></el-table-column></span>
            <el-table-column :label="item.propName" :property="item.prop" v-for="(item) in tableColumnList"
                             :key="item.prop" sortable>
                <template slot-scope="scope">
                    <span v-if="item.propName==='课程名'||item.propName==='班级'||item.propName==='课程码'"><el-tag>{{scope.row[scope.column.property]}}</el-tag></span>
                    <span v-else-if="item.propName==='教室'">
                        <el-tooltip class="item" effect="dark" :content="scope.row.classroomTip" placement="top">
                          <el-button @click="showEditClassroom(scope.row)">{{scope.row[scope.column.property]==null?'点击分配教室':scope.row[scope.column.property]}}</el-button>
                        </el-tooltip>
                    </span>
                    <span v-else-if="item.propName==='教师'">
                        <el-tooltip class="item" effect="dark" :content="scope.row.teacherTip" placement="top">
                          <el-button @click="showEditTeacher(scope.row)">{{scope.row[scope.column.property]==null?'点击分配教师':scope.row[scope.column.property]}}</el-button>
                        </el-tooltip>
                    </span>
                    <span v-else>{{scope.row[scope.column.property]}}</span>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="175px">
                <template slot-scope="scope">
                    <el-button @click="importRow(scope.row)" type="warning" size="mini"
                               icon="el-icon-download"></el-button>
                    <!--                    <el-button @click="showEdit(scope.row)" type="danger" size="mini"-->
                    <!--                               icon="el-icon-edit"></el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="padding-top: 15px"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="current"
                       :page-sizes="[1, 2, 3, 6, 15]"
                       :page-size="size"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="this.total">
        </el-pagination>
        <el-dialog
                title="教室分配"
                :visible.sync="dialogVisibleClassroom"
                width="30%">
            <div>
                <div>
                    <el-tag type="danger">教室分配</el-tag>
                    <el-cascader :options="optionsClassroom" clearable
                                 v-model="updateTableData.classroomId"></el-cascader>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleClassroom = false">取 消</el-button>
                <el-button type="primary" @click="updateOrInsertDataClassroom">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="课程分配"
                :visible.sync="dialogVisibleTeacher"
                width="30%">
            <div v-for="(teacherName,index) in optionsTeacher" :key="index">
                <el-popover
                        placement="right"
                        width="400"

                        trigger="click">
                    <el-table :data="teacherName.list" show-summary
                    >
                        <el-table-column width="150" property="courseName" label="教授课程"></el-table-column>
                        <el-table-column width="70" property="classNumber" label="班级数"></el-table-column>
                        <el-table-column width="70" property="time" label="学时"></el-table-column>
                        <el-table-column width="70" property="timeAll" label="总学时"></el-table-column>
                    </el-table>
                    <el-button slot="reference" @click="updateNewTeacher(teacherName.username)">{{teacherName.affiliation}}--{{teacherName.name}}</el-button>
                </el-popover>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleTeacher = false">取 消</el-button>
                <el-button type="primary" @click="updateOrInsertDataTeacher">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

    export default {
        name: "TeacherCourseDistribution",
        methods: {
            handleSelectionChange(val) {
                this.batchIds = val;
            },
            batch(temp) {
                this.$confirm('此操作牵涉到' + this.batchIds.length + '条数据,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = '?';
                    this.batchIds.forEach(item => {
                        ids += 'ids=' + item.id + '&';
                    });
                    if (temp === 'merge') {
                        this.$message('merge---' + ids);
                    } else if (temp === 'split') {
                        this.$message('split---' + ids);
                    }
                    // this.deleteRequest('/Excel/deleteBatchIds'+ids).then(resp=>{
                    //     if(resp){
                    //         this.select();
                    //     }
                    // })
                })
            },
            importRow(row) {
                this.$message("正在研发" + row)
            },
            updateOrInsertDataClassroom() {
                // if (this.updateTableData.classroomId != null) {
                //     var classrooId = this.updateTableData.classroomId[1];
                // }
                // console.log(this.updateTableData)
                this.getRequest('/courseDistribution/distributionRoom/' + this.currentRow.id + '/' + this.updateTableData.classroomId[1]).then(resp => {
                    // 看一下返回信息
                    if (resp) {
                        this.select();
                        this.dialogVisibleClassroom = false
                    }
                });
            },
            updateNewTeacher(username){
                this.updateTableData.userId = username;
            },
            updateOrInsertDataTeacher() {
                this.getRequest('/courseDistribution/distributionTeacher/' + this.currentRow.id + '/' + this.updateTableData.userId).then(resp => {
                    // 看一下返回信息
                    if (resp) {
                        this.dialogVisibleTeacher = false;
                        this.select();
                    }
                });
            },
            showEditTeacher(row) {
                this.updateTableData = [];
                this.initTeacher(row.courseId);
                this.currentRow = row;
                this.dialogVisibleTeacher = true;
            },
            showEditClassroom(row) {
                this.updateTableData = [];
                this.currentRow = row;
                this.initClassroom();
                this.dialogVisibleClassroom = true;
            },
            initClassroom() {
                this.postRequest('/classroom/selectParam/1/999', this.classroom).then(resp => {
                    // 看一下返回信息
                    if (resp) {
                        // console.log(JSON.stringify(resp));
                        this.initClassroomFlush(resp.data);
                    }
                })
            },
            initClassroomFlush(data) {
                // console.log(data);
                // console.log(data[""+1+""].length);
                this.optionsClassroom = [{
                    label: "机房",
                    values: '1',
                    children: [],
                }, {
                    label: "多媒体",
                    values: '2',
                    children: [],
                }, {
                    label: "有电源",
                    values: '3',
                    children: [],
                }, {
                    label: "普通教室",
                    values: '4',
                    children: [],
                }];

                for (let i = 0; i < 4; i++) {
                    for (let j = 0; j < data["" + (i + 1) + ""].length; j++) {
                        let kv = {
                            label: data["" + (i + 1) + ""][j].name + "-" + data["" + (i + 1) + ""][j].num,
                            value: data["" + (i + 1) + ""][j].id,
                        };
                        console.log(kv);
                        this.optionsClassroom[i].children.push(kv);
                    }
                }
            },
            initTeacher(courseId) {
                this.getRequest('/courseDistribution/selectTeacherNameAndAffiliation/'+courseId).then(resp => {
                    // 看一下返回信息
                    if (resp) {
                        this.optionsTeacher = resp.data;
                    }
                })
            },
            focusInfoTeacher(userId) {
                this.getRequest('/courseDistribution/selectTeacherWork/'+userId).then(resp => {
                    // 看一下返回信息
                    if (resp) {
                        this.tipTeacherData= resp.data;
                    }
                })
                return this.tipTeacherData;
            },
            updateTeacher(username){
                this.currentRow.userId =  username;
                // this.courseItem = this.focusInfoTeacher(username)
            },
            select() {
                this.postRequest('/courseDistribution/select/' + this.current + '/' + this.size, this.formInline).then(resp => {
                    // 看一下返回信息
                    // console.log(this.formInline);
                    // alert(JSON.stringify(resp));
                    if (resp) {
                        this.tableData = resp.data.records;
                        this.total = resp.data.total;
                        this.updateTableData = [];
                    }
                })
            },
            // 分页改变每页数量
            handleSizeChange(size) {
                this.size = size;
                this.select();
            },
            // 分页改变当前页数
            handleCurrentChange(current) {
                this.current = current;
                this.select();
            },
            // 动态表头
            menuChange(item) {
                // 注意  我这里都用的假数据，要从后台获取tableColumnList和dataList的时候
                //，每一次调用menuChange都要重新获取tableColumnList和dataList，保证属性和数据是对应的
                let flag = true
                for (let i = 0; i < this.checkArr.length; i++) {
                    if (this.checkArr[i] === item.propName) {
                        flag = false
                        break
                    }
                }
                if (!flag) {
                    this.tableColumnList.push(item)
                }
                if (flag) {
                    Array.prototype.contains = function (obj) {
                        let j = this.length;
                        while (j--) {
                            if (this[j] === obj) {
                                return j; // 返回的这个 i 就是元素的索引下标，
                            }
                        }
                        return false
                    }
                    this.tableColumnList.splice(this.tableColumnList.contains(item), 1)
                }
            },
            reset() {
                this.formInline.classId = null;
                this.formInline.className = null;
                this.formInline.courseId = null;
                this.formInline.name = null;
                this.select();
            },
        },
        mounted() {
            this.select();
        },
        data() {
            return {
                tokenStr: localStorage.getItem('tokenStr'),
                // 分页
                size: 6,
                current: 1,
                total: 0,
                // dialogVisible: false, // 编辑弹出框显示控制
                dialogVisibleTeacher: false, // 编辑弹出框显示控制
                dialogVisibleClassroom: false, // 编辑弹出框显示控制
                updateTableData: {
                    "classId": "",
                    "className": "",
                    "classroomId": 0,
                    "courseId": "",
                    "courseName": "",
                    "id": 0,
                    "logicTime": 0,
                    "remark": "",
                    "userId": "",
                    "userName": "",
                    "teacherTip": "",
                    "classroomTip": "",
                },
                classroom: {
                    "id": 0,
                    "name": "",
                    "num": 0,
                    "remark": "",
                    "type": "",
                    "workable": 0
                },
                teacher: {
                    "address": "",
                    "affiliation": "",
                    "id": 0,
                    "name": "",
                    "userName": ""
                },
                tableData: null,
                tableColumnList:
                    [
                        {prop: 'courseId', propName: '课程码'},
                        {prop: 'courseName', propName: '课程名'},
                        {prop: 'classId', propName: '班级'},
                        {prop: 'className', propName: '教室'},
                        {prop: 'userName', propName: '教师'},
                    ],
                optionalColumnList:
                    [
                        {prop: 'id', propName: '业务主键'},
                        {prop: 'classroomId', propName: '教室id'},
                        {prop: 'logicTime', propName: '逻辑时间'},
                        {prop: 'userId', propName: '用户id'},
                        {prop: 'remark', propName: '注意事项'},
                    ],
                checkArr: [],
                formInline: {
                    "classId": "",
                    "className": "",
                    "courseId": "",
                    "courseName": "",
                    "userName": "",
                },
                currentRow: '', // 存储当前行数据
                batchIds: [], //批量删除多选框
                optionsClassroom: [],
                optionsTeacher: [],
                tipTeacherData: [],// 存储分配是展示tip
                courseItem: [],
            }
        }
    }
</script>
<style>
    .updatePosInput {
        width: 180px;
        margin: 8px;
    }
</style>